package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.MyBaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        log.info("请求地址{}",requestURI);
        String urls[] = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        boolean check = check(urls, requestURI);
        if (check) {
            log.info("放行路径{}",requestURI);
            filterChain.doFilter(req,res);
            return;
        }
        if ( null!=req.getSession().getAttribute("employee")) {
            MyBaseContext.setId((Long) req.getSession().getAttribute("employee"));
            filterChain.doFilter(req,res);
            return;
        }
        if (null!= req.getSession().getAttribute("user")) {
            MyBaseContext.setId((Long) req.getSession().getAttribute("user"));
            filterChain.doFilter(req,res);
            return;
        }
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String urls[],String requestURI){
        for (String url : urls) {
            boolean mc = PATH_MATCHER.match(url, requestURI);
            if (mc) {
                return true;
            }
        }
        return false;

    }
}
